package com.zc.websocket.handler.event;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zc.websocket.constant.Method;
import com.zc.websocket.core.TextWebSocketFrameHandler;
import com.zc.websocket.dto.param.EventError;
import com.zc.websocket.dto.param.LoginError;
import com.zc.websocket.dto.result.*;
import com.zc.websocket.enums.ErrorCodeEnum;
import com.zc.websocket.handler.AbstractSender;
import com.zc.websocket.handler.ResultSendable;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.lang.reflect.Type;
import java.util.logging.Logger;

/**
 * 事件消息发送器
 * @author Athena-xiepufeng
 */
public class EventResultSender extends AbstractSender implements ResultSendable
{

    private static final Logger log = Logger.getLogger(EventResultSender.class.getName());

    @Override
    public void send(CmdExeResult result)
    {
        if (result.getCode() != ErrorCodeEnum.ERR_OK.getInternalCode())
        {
            EventError eventError = new EventError();
            eventError.setCode(result.getCode());
            eventError.setMessage(result.getMessage());
            eventError.setMethod(Method.EVENT);

            ErrorMsg<EventError> errorMsg = new ErrorMsg<>();
            errorMsg.setError(eventError);

            Gson gson = new Gson();
            Type type = new TypeToken<ErrorMsg<EventError>>()
            {
            }.getType();
            String msg = gson.toJson(errorMsg, type);

            TextWebSocketFrameHandler textWebSocketFrameHandler = getChannelHandler();
            if (textWebSocketFrameHandler == null)
            {
                return;
            }

            textWebSocketFrameHandler.getCtx().channel().writeAndFlush(new TextWebSocketFrame(msg));
            return;
        }

        EventResult eventResult = new EventResult();
        eventResult.setMessage(result.getMessage());
        eventResult.setCode(result.getCode());
        eventResult.setMethod(Method.EVENT);

        ResultMsg<EventResult> resultMsg = new ResultMsg<>();
        resultMsg.setResult(eventResult);

        Gson gson = new Gson();
        Type type = new TypeToken<ResultMsg<EventResult>>()
        {
        }.getType();

        String msg = gson.toJson(resultMsg, type);
        TextWebSocketFrameHandler textWebSocketFrameHandler = getChannelHandler();
        if (textWebSocketFrameHandler == null || textWebSocketFrameHandler.getCtx() == null)
        {
            log.warning("事件请求失败, channel 可能被关闭" );
            return;
        }

        // 事件请求相应结果到客户端
        textWebSocketFrameHandler.getCtx().channel().writeAndFlush(new TextWebSocketFrame(msg));
    }

}
